package util;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SessionHelper {
	
	private static Logger log = Logger.getLogger(SessionHelper.class);
	
	private static SqlSessionFactoryBean sqlSessionFactoryBean;
	
	@Autowired//不支持static修饰的变量，所以只能注解在sqlSessionFactoryBean的set方法上
	public void setSqlSessionFactoryBean(SqlSessionFactoryBean sqlSessionFactoryBean) {
		SessionHelper.sqlSessionFactoryBean = sqlSessionFactoryBean;
	}


	public static SqlSession getSession(){
		log.info("Spring 注入的 sqlSessionFactoryBean 内容:"+sqlSessionFactoryBean);
		try {
			return sqlSessionFactoryBean.getObject().openSession();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
